// 合并数组
const sumTopic = function (arr) {
    return arr.reduce((pre, cur) => pre.concat(cur.data || cur.value), []);
};
export default {
    namespaced: true,
    state: {
        topicIndex: 0,
        topicRulesList: [],
        topicList: [],
    },
    getters: {
        getTopicId: (state) => {
            if (uni.$u.test.empty(state.topicList)) return 0;
            return state.topicList[state.topicIndex].topic_id;
        },
    },
    mutations: {
        init(state, data) {
            state.topicIndex = 0;
            if (uni.$u.test.empty(data)) {
                state.topicIndex = 0;
                state.topicList = [];
                state.topicRulesList = [];
            } else {
                state.topicList = sumTopic(data);
                state.topicRulesList = data;
            }
        },
        // 上一题
        prev(state) {
            state.topicIndex -= 1;
        },
        // 下一题
        next(state) {
            state.topicIndex += 1;
        },
        // 点击答题卡跳转到对应的题
        change(state, index) {
            state.topicIndex = index;
        },
        // 保存正确的答案
        changeCorrectAnswer(state, { id, answer }) {
            if (!uni.$u.test.empty(state.topicList)) {
                const topic = state.topicList.find(
                    (item) => item.topic_id == id
                );
                topic.correct_answer = answer; // 正确的答案
            }
        },
        // 保存选择的答案
        changeCurrentAnswer(state, { id, answer }) {
            if (!uni.$u.test.empty(state.topicList)) {
                const topic = state.topicList.find(
                    (item) => item.topic_id == id
                );
                topic.current_answer = answer; // 选择的答案
            }
        },
        // 提交答案
        submitCurrentAnswer(state, { id, is_right }) {
            if (!uni.$u.test.empty(state.topicList)) {
                const topic = state.topicList.find(
                    (item) => item.topic_id == id
                );
                topic.has_answered = 1; // 已答
                topic.is_right = is_right; // 答案是否正确
            }
        },
    },
};
